package com.dimld.api;

import com.dimld.connect.ConnectorI;
import com.google.gson.Gson;
import com.dimld.connect.MsgReaderI;
import com.dimld.connect.http.HttpHandle;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Deque;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * HTTP消息解析
 *
 * @author 苏雷
 */
public class ApiHttpMsg extends ApiBaseMsg implements MsgReaderI {
    private final Logger httpLog = LoggerFactory.getLogger("http");
    final         Gson   gson    = new Gson();

    @Override
    public void connect(ConnectorI conn) {
        httpLog.info("[" + conn.getFullIP() + "]连接成功");
    }

    @Override
    public void read(String json, ConnectorI conn) {
        HttpHandle         httpHandle = (HttpHandle) conn;
        HttpServerExchange exchange   = httpHandle.getExchange();
        HttpString         requestMethod = exchange.getRequestMethod();
        String             method        = requestMethod.toString();
        String             response_text = "{\"RESPONSE\":\"success\"}";
        switch (method.toUpperCase()) {
            case "GET":
                response_text = get(exchange);
                break;
            case "POST":
                response_text = post(json);
                break;
            case "PUT":
                break;
            case "DELETE":
                break;
            default:
        }
        conn.send(response_text);
    }

    private String get(HttpServerExchange httpServerExchange) {
        String                     response_text   = "get request execute finish";
        String                     uri             = httpServerExchange.getRequestURI();
        Map<String, Deque<String>> queryParameters = httpServerExchange.getQueryParameters();
        if (uri.contains("?")) {
            String[] url = uri.split("\\?");
            uri = url[0];
        }
        httpLog.debug("uri = {}", uri);
        switch (uri) {
            case "/prometheus":
                break;
            case "/open/v1/inviteAgent":
            case "/inviteAgent":
                break;
            case "/ccs/get_group_idle_count":
                break;
            default:
                response_text = "not find this action";
        }
        return response_text;
    }

    private String post(String json) {
        String response_text = "post request execute finish";
        try {

        } catch (Exception e) {
            httpLog.error("解析消息错误，message=" + json, e);
        }
        return response_text;
    }

    @Override
    public void disconnect(ConnectorI conn) {
        httpLog.info("[" + conn.getFullIP() + "]断开连接");
    }
}
